<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Facades\Cache;
use App\Services\ApplyGoldCoinWithdrawSandPay\ApplyGoldCoinWithdrawSandPay;
use App\Services\ApplyGoldCoinWithdrawSandPay\ApplyGoldCoinWithdrawSandPayRequest;


class WithdrawsSandPayController extends Controller
{
	public function store()
    {
    	$lock = Cache::lock('withdraw', 30);

    	try {

    		if (! $lock->get()) fail('太快了，请再试一次');

    		$request = app(ApplyGoldCoinWithdrawSandPayRequest::class);

    		$user = $request->user();

    		need_paycode($user);

		    $withdraw = $user->withdraws()->where('method','sandpay')->orderByDesc('id')->first();

		    if($withdraw){
		    	if($withdraw->status  == 'pending'){
		    		fail('您有审核中的提现记录，不可重复提交');
		    	}
		    }

		    app(ApplyGoldCoinWithdrawSandPay::class, [
			    'user' => $user,
			    'coins' => $request->coins,
			    'payCode' => $request->pay_code,
		    ])->apply();

		    $user->resetPayCodeTry();

	    } finally {
    		$lock->release();
	    }

	    return response(null, 204);
    }


	public function record()
	{
		$withdraw = request()->user()->withdraws()->where('method','sandpay')->orderByDesc('id')->first();
		if(!$withdraw){
			return response()->json(['code' => 200, 'msg'=> 'success', 'data' => null ]);
		}
		return response()->json(['code' => 200, 'msg'=> 'success', 'data' => $withdraw->toArray() ]);
	}
}
